package com.sat.client.adapter

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

class EqualSquareLayoutManager(private val spacing: Int) : RecyclerView.LayoutManager() {

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.WRAP_CONTENT,
            RecyclerView.LayoutParams.WRAP_CONTENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
        if (itemCount == 0) {
            detachAndScrapAttachedViews(recycler)
            return
        }

        detachAndScrapAttachedViews(recycler)

        val parentWidth = width
        val totalSpacing = spacing * (itemCount - 1)
        val itemWidth = (parentWidth - totalSpacing) / itemCount // 平分宽度

        var leftOffset = 0

        for (i in 0 until itemCount) {
            val view = recycler.getViewForPosition(i)
            addView(view)
            measureChildWithMargins(view, 0, 0)
            val itemSize = itemWidth.coerceAtMost(height)
            layoutDecorated(view, leftOffset, 0, leftOffset + itemSize, itemSize)
            leftOffset += itemWidth + spacing
        }
    }

    override fun canScrollHorizontally(): Boolean {
        return false // 不允许水平滚动
    }

    override fun canScrollVertically(): Boolean {
        return false // 不允许垂直滚动
    }
}
